<template>
  <div id="wrapper">
   <!-- <img id="logo" src="~@/assets/logo.png" alt="electron-vue"> -->
    <main>
      <!-- 左侧内容 -->
      <div class="left-side">
        <span class="title">
          源EXCEL路径:
        </span>
        <!-- <system-information></system-information> -->
        
        <input class='pathinput' type='text' placeholder='请设置excel路径' disabled="disabled" :value=excelPath />
        <p><button class="chooseBt" @click='chooseExcel()'>选择</button></p>
        <br>
        <span class="title">
          CSV导出路径:
        </span>
        <!-- <system-information></system-information> -->
        <input class='pathinput' type='text' placeholder='请设置CSV导出路径' disabled="disabled" :value=csvPath />
        <p><button class="chooseBt" @click='chooseCsv()'>选择</button></p>
        <br>
        <hr>
        <br>
        <span class="title">
          JSON导出路径:
        </span>
        <!-- <system-information></system-information> -->
        <input class='pathinput' type='text' placeholder='请设置JSON导出路径' disabled="disabled" :value=jsonPath />
        <p><button class="chooseBt" @click='chooseJson()'>选择</button></p>
        <br>
        <hr>
        <!-- <span class="input-group-addon12">
          <input id="duoyuyan_checkbox" type="checkbox" @click="click_duoyuyan($event)"> 多语言替换
        </span> -->

        <span style=" margin-top:10px">
          <h4>多语言替换文件:</h4>
          <select id='language_select' style="font-size:16px; margin-right:10px; width:300px" @click='selectLanguage($event)'>
            <option >不处理</option>
            <option v-for="item in languageFiles" :key="item" :value="item" :class='item.class'>{{item}}</option>
          </select>
          
        </span>

        <br>
        <span class="input-group-addon">
          <input id="hebing_checkbox" type="checkbox" @click="click_hebing($event)" > 
          <span style="font-size:15px;font-weight:bold;">进行合并操作</span>
        </span>
        
        <div v-if="config.is_hebingcheck" class='hebing_div'>

          <span class="title">
            合并源路径:
          </span>
          <br>
          <!-- <system-information></system-information> -->
          <input class='pathinput' type='text' placeholder='请设置替换源路径' disabled="disabled" :value=replacePath style="width:100%"/>
          <p><button class="chooseBt" @click='chooseReplace()'>选择</button></p>
        </div>
      </div>

      <!-- 右侧内容 -->
      <div class="right-side">
          <h3>输出日志:</h3>
          <div class='logList' id='logList'>
              <ul>
                <li v-for='(item) in logData' v-bind:key='item.text' :class='item.class'>
                    {{item.text}}
                </li>
              </ul>
          </div>
      </div>
    </main>
    <hr>
    <div class="bottom">
        <button @click="csvCheck()" style="font-size:28px">CSV校验</button>
        <h4 >{{desc}}</h4>
        <button @click="excelTocsv()" style="font-size:28px">开始转换</button>
    </div>

     
  </div>
</template>

<script>
let electron = require("electron");
import { BrowserWindow, ipcRenderer } from "electron";
var fs = require("fs");
var path = require("path");
import { remote } from "electron";

import esnm from "./excel_csv_name_mapping.js";
import cf from "./content_filter.js";
import ch from "./content_hebing.js";
import cr from "./content_replace.js";
import jc from "./json_convert.js";
import XLSX from "xlsx";
import { setInterval, clearInterval } from "timers";
var config_file_path = "";
var self = null;
// import dialog  from 'electron';
export default {
  name: "landing-page",
  components: {},
  data() {
    return {
      excelPath: "",
      csvPath: "",
      jsonPath: "",
      replacePath: "",
      config: {},
      logData: [],
      languageFiles: [],
      desc: "选好目录，点击‘开始转换’"
    };
  },

  beforeMount: function() {
    config_file_path = path.join(remote.app.getPath("userData"), "config.txt");
  },

  mounted() {
    
    self = this;
    fs.exists(config_file_path, function(exist) {
      if (exist) {
        var content = fs.readFileSync(config_file_path, { encoding: "utf-8" });
        self.config = JSON.parse(content);
        self.excelPath = self.config.epath;
        self.csvPath = self.config.cpath;
        self.jsonPath = self.config.jpath;
        self.replacePath = self.config.replacePath;

        if (self.config.is_hebingcheck)
          document.getElementById("hebing_checkbox").checked = true;

        if (self.config.duoyuyan)
          document.getElementById("duoyuyan_checkbox").checked = true;

        //多语言文件筛选
        self.$options.methods.languageFilesSync();

        setTimeout(() => {
          //根据配置设置多语言默认选择的文件
          var select = document.getElementById("language_select"); // self.languageSelectValue;
          for (var i = 0; i < select.options.length; i++) {
            if (
              self.config.languageSelectValue.indexOf(
                select.options[i].value
              ) == 0
            ) {
              select.options[i].selected = "selected";
            }
          }
        }, 0);
      }
    });
    // self.$options.methods.csvCheck();
  },
  methods: {
    // open(link) {
    //   this.$electron.shell.openExternal(link);
    // },

    languageFilesSync() {
      self.languageFiles.splice(0);
      var path = self.excelPath + "/../toServer/多语言替换表";
      var pa = fs.readdirSync(path);
      pa.forEach(function(ele, index) {
        var info = fs.statSync(path + "/" + ele);
        if (info.isDirectory()) {
        } else {
          // console.log("file: " + ele);
          if (ele.indexOf(".xlsx") > 0) self.languageFiles.push(ele);
        }
      });
    },

    selectLanguage(event) {
      self.config.languageSelectValue = event.currentTarget.value;

      this.$options.methods.saveConfig();
    },

    click_hebing(event) {
      self.config.is_hebingcheck = event.currentTarget.checked;
      self.$options.methods.saveConfig();
    },

    click_duoyuyan(event) {
      self.config.duoyuyan = event.currentTarget.checked;
      self.$options.methods.saveConfig();
    },

    clearLog() {
      self.logData.splice(0, self.logData.length);
    },

    addLog(text, isError) {
      var item = {};
      item.text = text;
      item.class = "log_normal";
      if (isError) item.class = "log_error";

      self.logData.push(item);
      var div = document.getElementById("logList");
      div.scrollTop = div.scrollHeight;
    },

    saveConfig() {
      fs.writeFileSync(config_file_path, JSON.stringify(self.config));
    },

    csvCheck() {
      // console.log(electron.remote.BrowserWindow);
      // ipcRenderer.sendSync('checkCSV', 'path');
      const winURL =
        process.env.NODE_ENV === "development"
          ? `http://localhost:9080/#checkCSV`
          : `file://${__dirname}/index.html?#checkCSV`;

      var mainWindow = electron.remote.getCurrentWindow();
      var checkWindow = new electron.remote.BrowserWindow({
        width: 1280,
        height: 720,
        // modal: true,
        // parent: mainWindow,
        maximizable: false,
        resizable: false,
        show: false
        // backgroundColor: '#eee',
      });
      checkWindow.setResizable(false);
      checkWindow.setMenu(null);
      checkWindow.setMaximizable(false);
      checkWindow.loadURL(winURL);
      checkWindow.once("ready-to-show", () => {
        mainWindow.hide();
        checkWindow.show();
      });

      checkWindow.on("closed", () => {
        checkWindow = null;
        mainWindow.show();
      });
    },
    excelTocsv() {
      var error = {};
      // console.log(fileNames);
      self.$options.methods.clearLog();
      cr.prepareDictionary(
        self.excelPath + "/../多语言替换表/" + self.config.languageSelectValue
      );
      // if (error.msg) {
      //   this.$options.methods.addLog(error.msg);
      // }

      esnm.__init(this.csvPath, () => {
        var fileNames = [];
        var totalTime = +new Date();
        self.desc = "开始转换";

        if (self.config.duoyuyan) self.desc += " <多语言替换>";
        self.$options.methods.readDirSync(self.excelPath, fileNames);

        var index = 0;
        var inter_id = setInterval(() => {
          if (index < fileNames.length) {
            var file_name = fileNames[index];
            var tail_index = file_name.indexOf(".");
            file_name = file_name.slice(0, tail_index);

            var beginTime = +new Date();
            //只导出在中英文数值表名对照的excel
            if (esnm.get_csv_name(file_name)) {
              //  alert(esnm.get_csv_name(file_name))
              var result = self.$options.methods.ExcelConvert(
                self.excelPath,
                self.csvPath,
                fileNames[index],
                esnm.get_csv_name(file_name),
                error
              );

              if (!result) {
                self.desc = "导出异常";
                clearInterval(inter_id);
                self.$options.methods.addLog(
                  fileNames[index] + "导出错误：" + error.msg,
                  true
                );
                // alert(fileNames[index] + "导出错误：" + error.msg);
                return;
              }

              var now = +new Date();
              var logitem = fileNames[index] + "(" + (now - beginTime) + "ms)";

              if (error.dyy_count > 0)
                logitem += "--多语言替换:" + error.dyy_count + "处";

              self.$options.methods.addLog(logitem);
            }
            index++;
          } else {
            clearInterval(inter_id);
            self.desc = "转换完成。 耗时：" + (+new Date() - totalTime) + "ms";
            self.$options.methods.addLog("导出完成");
          }
        }, 0);
      });
    },

    readDirSync(path, fileNames) {
      var self = this;
      var pa = fs.readdirSync(path);
      pa.forEach(function(ele, index) {
        var info = fs.statSync(path + "/" + ele);
        if (info.isDirectory()) {
          console.log("dir: " + ele);
          self.readDirSync(path + "/" + ele, fileNames);
        } else {
          // console.log("file: " + ele);
          if (ele.indexOf(".xlsx") > 0) fileNames.push(ele);
        }
      });
    },

    chooseExcel() {
      electron.remote.dialog.showOpenDialog(
        null,
        { properties: ["openFile", "openDirectory", "multiSelections"] },
        filePaths => {
          if (filePaths && filePaths.length > 0) {
            this.excelPath = filePaths[0];
            self.config.epath = this.excelPath;
            self.$options.methods.saveConfig();
          }
        }
      );
    },

    chooseCsv() {
      electron.remote.dialog.showOpenDialog(
        null,
        { properties: ["openFile", "openDirectory", "multiSelections"] },
        filePaths => {
          if (filePaths && filePaths.length > 0) {
            this.csvPath = filePaths[0];
            self.config.cpath = this.csvPath;
            self.$options.methods.saveConfig();
          }
        }
      );
    },

    chooseJson() {
      electron.remote.dialog.showOpenDialog(
        null,
        { properties: ["openFile", "openDirectory", "multiSelections"] },
        filePaths => {
          if (filePaths && filePaths.length > 0) {
            this.jsonPath = filePaths[0];
            self.config.jpath = this.jsonPath;
            self.$options.methods.saveConfig();
          }
        }
      );
    },

    chooseReplace() {
      electron.remote.dialog.showOpenDialog(
        null,
        { properties: ["openFile", "openDirectory", "multiSelections"] },
        filePaths => {
          if (filePaths && filePaths.length > 0) {
            this.replacePath = filePaths[0];
            self.config.replacePath = this.replacePath;
            self.$options.methods.saveConfig();
          }
        }
      );
    },

    ExcelConvert(epath, cpath, fileName, csv_name, err) {
      //var files = e.target.files;

      var output_csv_path = cpath;
      var output_json_path = self.config.jpath; //cpath + "/json/";
      // if(!fs.existsSync(output_csv_path))
      // fs.mkdirSync(output_csv_path);
      if (!fs.existsSync(output_json_path)) fs.mkdirSync(output_json_path);

      var path = epath + "/" + fileName;
      var workbook;

      //读取excel
      var data;
      try {
        data = fs.readFileSync(path, "binary"); //, function(err, data) {
      } catch (e) {
        err.msg = e.message;
        return false;
      }

      try {
        workbook = XLSX.read(data, { type: "binary" }); // 以二进制流方式读取得到整份excel表格对象
      } catch (e) {
        err.msg = "read error:" + e;
        return false;
      }

      var duoyuyan_count = 0;
      // 遍历每张表读取
      for (var sheet in workbook.Sheets) {
        if (workbook.Sheets.hasOwnProperty(sheet)) {
          //转为json对象进行验证操作
          var json = XLSX.utils.sheet_to_json(workbook.Sheets[sheet], {
            header: 1,
            blankrows: false
          });

          var replacePath = self.replacePath + "/" + fileName;
          // alert(replacePath);
          if (fs.existsSync(replacePath)) {
            if (!ch.replace(json, replacePath, err)) return false;

            var now = +new Date();
            var item = fileName + " 合并成功";
            self.$options.methods.addLog(item);
          }

          if (!cf.format(json, err)) return false;

          //多语言替换
          if (!cr.replace(json, err)) return false;

          var sheetfromjson = XLSX.utils.json_to_sheet(json, {
            skipHeader: true
          });

          console.log(json);
          //sheet -->csv
          var csvString = XLSX.utils.sheet_to_csv(sheetfromjson, {
            blankrows: false
          });

          // sheetfromjson = XLSX.utils.json_to_sheet(json, {
          //   skipHeader: true
          // });

          // var jsonObject = XLSX.utils.sheet_to_json(sheetfromjson, {
          //   blankrows: false,
          // });

          var csvPath = output_csv_path + "/" + csv_name + ".csv";
          var jsonPath = output_json_path + "/" + csv_name + ".json";

          var jsonString = jc.convert_to_string(json);
          try {
            fs.writeFileSync(csvPath, "\uFEFF" + csvString, {
              encoding: "utf-8"
            }); //function(err, data) {
            fs.writeFileSync(jsonPath, "\uFEFF" + jsonString, {
              encoding: "utf-8"
            });
          } catch (e) {
            if (e) err.msg = e.message;
            return false;
          }
          // if (err) {
          //   throw err;
          // }
          break; // 如果只取第一张表，就取消注释这行
        }
      }
      return true;
    }
  }

};
</script>

<style>
@import url("https://fonts.googleapis.com/css?family=Source+Sans+Pro");

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  font-family: Arial, Helvetica, sans-serif;
}

li {
  list-style-type: none;
}

#wrapper {
  background: radial-gradient(
    ellipse at top left,
    rgba(255, 255, 255, 1) 40%,
    rgba(229, 229, 229, 0.9) 100%
  );
  height: 100vh;
  /* padding: 30px 30px; */
  width: 100vw;
}

#logo {
  height: auto;
  margin-bottom: 10px;
  width: 160px;
}

main {
  display: flex;
  justify-content: space-between;
  height: 85vh;
  box-sizing: border-box;
  border: 1px solid rgb(56, 54, 54);
  padding: 20px;
}

main > div {
  flex-basis: 48%;
}

.left-side {
  display: flex;
  flex-direction: column;
  padding: 0;
}
.right-side {
  height: 100%;
  box-sizing: border-box;
}

.welcome {
  color: #555;
  font-size: 23px;
  margin-bottom: 10px;
}

.title {
  color: #2c3e50;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 6px;
  /* margin-left:20px; */
}

.pathinput {
  /* text-enable:false; */
  font-size: 16px;
}

.chooseBt {
  font-size: 16px;
  padding: 5px 10px;
  margin-top: 8px;
}

.bottom {
  display: flex;
  position: fixed;
  bottom: 1.6vh;
  width: 100%;
  left: 0;
  padding: 20px;
  justify-content: space-between;
  align-items: center;
  background-color: rgb(179, 166, 166);
  box-sizing: border-box;
}

.logList {
  height: 99%;
  width: 100%;
  padding: 10px 10px;

  overflow: scroll;
  overflow-x: hidden;
  border-left: 1px solid black;
  box-sizing: border-box;
}

.log_normal {
  color: black;
}
.log_error {
  color: red;
}

.hebing_div {
  box-sizing: border-box;
  border: 1px dotted gray;
}
</style>
